package com.cortex.pineapple.fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;

import com.cortex.pineapple.utilities.MessagesLog;
import com.cortext.pineapple.link.Link;

/**
 * @author Gal lavie
 * this class make icons search of webs in google 
 * this class get papayaCategoty and open new thread for each PapayaDocument found in PapayaCategory
 * when class finish search the class send message on finish to PapayaApplication
 * 
 *
 */

public class FetchIcons {
	private OnFetchIconsChangedListener onFetchIconsChangedListener;
	private StartIconThread startIconThread;


	public void setOnFetchIconsChangedListener(OnFetchIconsChangedListener Statechanged){
		this.onFetchIconsChangedListener = Statechanged;
	}

	public void startFetching(List<Link> links){
		if(isRunning()){
			startIconThread.cancel(true);
		}
		startIconThread = new StartIconThread();
		startIconThread.execute(links);
	}
	public void cancelFetching() {
		if(isRunning()){
			startIconThread.cancel(true);
		}
	}
	public boolean isRunning(){
		return (startIconThread != null)&&(startIconThread.getStatus() == Status.RUNNING)?true:false;
	}
	private class StartIconThread extends AsyncTask<List<Link>, IconLink, List<Link>>{

		@Override
		protected List<Link> doInBackground(List<Link>... params) {
			List<Link> links = params[0];

			for (Link link : links) {
				try {
					String iconUrl = "http://www.google.com/s2/favicons?domain=" + link.getUrl();
					publishProgress(new IconLink(link, DownloadImage(iconUrl)));
					Thread.sleep(10);
				} catch (Exception e) {
					Log.d(MessagesLog.APPLICATION_EXCEPTION, "exception when " +
							"fetch icon from favicons do nothing with this exception");
				}
			}

			return links;
		}
		@Override
		protected void onPreExecute() {
			if(onFetchIconsChangedListener != null){
				onFetchIconsChangedListener.timeLoadIconsStarted();
			}
		}
		@Override
		protected void onProgressUpdate(IconLink... values) {
			Link link = values[0].getLink();
			link.setIcon(values[0].getIcon());
		}
		@Override
		protected void onPostExecute(List<Link> result) {
			if(onFetchIconsChangedListener != null){
				onFetchIconsChangedListener.timeLoadIconsFinished(result);
			}
		}

	}
	private InputStream OpenHttpConnection(String urlString) throws IOException {
		InputStream in = null;
		int response = -1;

		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();

		if (!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");

		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			throw new IOException("Error connecting");
		}
		return in;
	}
	private Bitmap DownloadImage(String URL) {
		Bitmap bitmap = null;
		InputStream in = null;
		try {
			in = OpenHttpConnection(URL);
			bitmap = BitmapFactory.decodeStream(in);
			in.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return bitmap;
	}
	private class IconLink{
		private Link link;
		private Bitmap icon;

		public IconLink(Link document, Bitmap icon) {
			super();
			this.link = document;
			this.icon = icon;
		}

		public Link getLink() {
			return link;
		}
		public void setLink(Link link) {
			this.link = link;
		}
		public Bitmap getIcon() {
			return icon;
		}
		public void setIcon(Bitmap icon) {
			this.icon = icon;
		}

	}
	public interface OnFetchIconsChangedListener{
		void timeLoadIconsStarted();
		void timeLoadIconsFinished(List<Link> documents);
		void timeLoadIconsCancelled();
	}
}
